package com.wangshaoyu.music_player.repository;

import lombok.Data;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.springframework.stereotype.Repository;

import java.util.List;

@Mapper
@Repository
public interface RelationRepo {
    @Select("select tid from relations where aid = #{aid} order by rid")
    List<Integer> selectTidListByAid(@Param("aid") int aid);

    @Delete("delete from relations where aid = #{aid} and tid = #{tid}")
    void deleteByAidAndTid(@Param("aid") int aid, @Param("tid") int tid);

    @Insert({
            "<script>",
            "insert into relations (aid, tid) values ",
            "<foreach collection='tidList' item='id' separator=', '>",
                "(#{aid}, #{id}) ",
            "</foreach>",
            "</script>"})
    void insertBatch(@Param("aid") int aid, @Param("tidList") List<Integer> tidList);

    @Data
    class AidToCountDo {
        public Integer aid;
        public Integer count;
    }

    @Select({"<script>",
            "select aid, count(*) count from relations where aid in (",
            "<foreach collection='aidList' item='id' separator=', '>",
                "#{id}",
            "</foreach>",
            ") group by aid order by aid",
            "</script>"})
    List<AidToCountDo> selectCountGroupByAidList(@Param("aidList") List<Integer> aidList);

    @Data
    class TidToCountDo {
        public Integer tid;
        public Integer count;
    }

    @Select({"<script>",
            "select tid, count(*) count from relations where tid in (",
            "<foreach collection='tidList' item='id' separator=', '>",
                "#{id}",
            "</foreach>",
            ") group by tid order by tid",
    "</script>"})
    List<TidToCountDo> selectCountGroupByTidList(@Param("tidList") List<Integer> tidList);
}
